const imageCache: AnyObject = {};

export const loadImage = (src: string = ""): Promise<any> => {
    return new Promise((resolve, reject) => {
        if (imageCache[src]) {
            resolve(imageCache[src]);
        } else {
            const img = new Image();
            img.onload = () => {
                imageCache[src] = img;
                resolve(img);
            };
            img.onerror = reject;
            img.src = src;
        }
    });
};
export const getImageAdaptSize = async (
    img: any,
    {
        dir,
        stageWidth,
        stageHeight,
    }: {
        dir: EssayEvaluatorConfig["dir"];
        stageWidth: number;
        stageHeight: number;
    }
) => {
    if (dir === "vertical") {
        const height = img.height / (img.width / stageWidth);
        return { width: stageWidth, height };
    } else {
        const width = img.width / (img.height / stageHeight);
        return { width, height: stageHeight };
    }
};

export const addFieldsToMarksArr = (marksArr: any[], fields: AnyObject) => {
    for (let i = 0; i < marksArr.length; i++) {
        const marks = marksArr[i];
        for (const key in fields) {
            addFieldToMarks(marks, key, fields[key]);
        }
    }
};

export const addFieldToMarks = (marks: any[], key: string, value: any) => {
    for (let i = 0; i < marks.length; i++) {
        marks[i][key] = value;
    }
};

export function capitalizeWord(str: string) {
    return str.replace(/^\w/g, function (match) {
        return match.toUpperCase();
    });
}

export function isMobile() {
    const ua = window.navigator.userAgent.toLowerCase();
    return /android|iphone|ipad|ipod|blackberry|windows phone|opera mini|mobile/i.test(
        ua
    );
}
